<template>
  <div class="admin-content-page">
    <div class="page-header">
      <h1>活动管理</h1>
    </div>

    <!-- 页面头部操作区 -->
    <div class="header-actions">
      <div class="search-container">
        <el-input
            v-model="searchKeyword"
            placeholder="请输入活动标题或内容搜索"
            clearable
            style="width: 300px"
        >
          <template #append>
            <el-button icon="el-icon-search" @click="handleSearch"></el-button>
          </template>
        </el-input>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button type="primary" @click="handleAddActivity">新增活动</el-button>
      </div>
    </div>

    <!-- 活动列表表格 -->
    <el-table
        v-loading="loading"
        :data="activityList"
        style="width: 100%"
        border
    >
      <el-table-column prop="id" label="活动ID" width="80" align="center" />
      <el-table-column prop="title" label="活动标题" width="250" />
      <el-table-column prop="time" label="活动时间" width="180" />
      <el-table-column prop="location" label="活动地点" width="200" />
      <el-table-column prop="quota" label="名额" width="80" align="center" />
      <el-table-column prop="enrolled" label="已报名" width="80" align="center" />
      <el-table-column prop="status" label="状态" width="100" align="center">
        <template #default="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'danger'">
            {{ row.status === 1 ? '进行中' : '已结束' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180" align="center">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="handleEditActivity(row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDeleteActivity(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>

    <!-- 活动表单对话框 -->
    <el-dialog
        v-model="dialogVisible"
        :title="dialogTitle"
        width="60%"
        :before-close="handleCloseDialog"
    >
      <el-form
          ref="activityFormRef"
          :model="activityForm"
          label-width="120px"
          :rules="formRules"
      >
        <el-form-item label="活动标题" prop="title">
          <el-input v-model="activityForm.title" placeholder="请输入活动标题" />
        </el-form-item>
        <el-form-item label="活动内容" prop="content">
          <el-input
              v-model="activityForm.content"
              type="textarea"
              :rows="4"
              placeholder="请输入活动内容"
          />
        </el-form-item>
        <el-form-item label="活动时间" prop="time">
          <el-date-picker
              v-model="activityForm.time"
              type="datetime"
              placeholder="选择日期时间"
              style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="活动地点" prop="location">
          <el-input v-model="activityForm.location" placeholder="请输入活动地点" />
        </el-form-item>
        <el-form-item label="活动名额" prop="quota">
          <el-input-number
              v-model="activityForm.quota"
              :min="1"
              :max="1000"
              placeholder="请输入活动名额"
          />
        </el-form-item>
        <el-form-item label="活动状态" prop="status">
          <el-switch
              v-model="activityForm.status"
              :active-value="1"
              :inactive-value="0"
              active-color="#13ce66"
              inactive-color="#ff4949"
          />
        </el-form-item>
        <el-form-item label="活动图片">
          <el-upload
              class="avatar-uploader"
              :action="'/api/upload/image'"
              :show-file-list="false"
              :on-success="handleImageUploadSuccess"
              :before-upload="beforeUploadImage"
          >
            <img v-if="activityForm.image" :src="activityForm.image" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <div class="el-upload__tip">请上传活动图片</div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCloseDialog">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getActivities, addActivity, updateActivity, deleteActivity, getActivityById, updateActivityStatus } from '../../api/activities'

// 响应式数据
const activityList = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const searchKeyword = ref('')

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const activityFormRef = ref(null)
const activityForm = reactive({
  id: '',
  title: '',
  content: '',
  time: '',
  location: '',
  quota: 10,
  status: 1,
  image: ''
})

// 表单验证规则
const formRules = reactive({
  title: [
    { required: true, message: '请输入活动标题', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入活动内容', trigger: 'blur' },
    { min: 10, max: 500, message: '长度在 10 到 500 个字符', trigger: 'blur' }
  ],
  time: [
    { required: true, message: '请选择活动时间', trigger: 'change' }
  ],
  location: [
    { required: true, message: '请输入活动地点', trigger: 'blur' },
    { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  quota: [
    { required: true, message: '请输入活动名额', trigger: 'blur' },
    { type: 'number', min: 1, message: '名额不能小于1', trigger: 'blur' }
  ]
})

const formatDateTime = (value) => {
  if (!value) return ''
  const date = new Date(value)
  if (Number.isNaN(date.getTime())) {
    return ''
  }
  return date.toLocaleString()
}

const normaliseActivityRecord = (item) => ({
  ...item,
  time: formatDateTime(item.startTime || item.endTime || item.time),
  location: item.location || '',
  quota: item.quota ?? 0,
  status: item.status ?? 0,
  enrolled: item.currentParticipants ?? item.enrolled ?? 0,
  image: item.coverImage || item.image || '',
  startTime: item.startTime || item.time || null,
  endTime: item.endTime || item.time || null
})

// 加载活动列表
const loadActivities = async () => {
  loading.value = true
  try {
    // 确保参数类型正确
    const params = {
      current: Number(currentPage.value),
      size: Number(pageSize.value),
      keyword: searchKeyword.value
    }
    console.log('管理员加载活动列表参数:', params)
    const result = await getActivities(params)
    if (result?.success) {
      const records = Array.isArray(result.data)
          ? result.data
          : (result.data?.records || [])
      activityList.value = records.map(normaliseActivityRecord)
      const totalValue = result.total ?? result.data?.total ?? records.length
      total.value = Number.isFinite(totalValue) ? Number(totalValue) : records.length
    } else {
      const message = result?.message || JSON.stringify(result ?? {})
      ElMessage.error('数据格式错误: ' + message)
    }
  } catch (error) {
    console.error('获取活动列表错误详情:', error)
    ElMessage.error(`获取活动列表失败: ${error.message || '未知错误'}`)
    // 如果是400错误，可能是参数问题
    if (error.message.includes('400')) {
      ElMessage.warning('请求参数可能有误，请刷新页面重试')
    }
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  loadActivities()
}

// 分页处理
const handleSizeChange = (size) => {
  pageSize.value = size
  loadActivities()
}

const handleCurrentChange = (current) => {
  currentPage.value = current
  loadActivities()
}

// 新增活动
const handleAddActivity = () => {
  dialogTitle.value = '新增活动'
  // 重置表单
  Object.keys(activityForm).forEach(key => {
    if (key === 'status') {
      activityForm[key] = 1
    } else if (key === 'quota') {
      activityForm[key] = 10
    } else {
      activityForm[key] = ''
    }
  })
  dialogVisible.value = true
}

// 编辑活动
const handleEditActivity = (row) => {
  dialogTitle.value = '编辑活动'
  // 复制行数据到表单
  Object.assign(activityForm, { ...row })
  dialogVisible.value = true
}

// 删除活动
const handleDeleteActivity = async (id) => {
  try {
    await ElMessageBox.confirm(
        '确定要删除该活动吗？删除后数据将无法恢复',
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    )
    const result = await deleteActivity(id)
    if (result?.success) {
      ElMessage.success('删除成功')
      loadActivities()
    } else {
      ElMessage.error(result.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除活动错误:', error)
      ElMessage.error(error.message || '删除失败')
    }
  }
}

// 关闭对话框
const handleCloseDialog = () => {
  dialogVisible.value = false
  if (activityFormRef.value) {
    activityFormRef.value.resetFields()
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!activityFormRef.value) return

  try {
    await activityFormRef.value.validate()

    // 处理日期格式
    const formData = { ...activityForm }
    if (formData.time instanceof Date) {
      formData.time = formData.time.toISOString()
    }

    let result
    if (formData.id) {
      // 编辑模式
      result = await updateActivity(formData.id, formData)
      if (result?.success) {
        ElMessage.success('更新成功')
      } else {
        ElMessage.error(result.message || '更新失败')
        return
      }
    } else {
      // 新增模式
      result = await addActivity(formData)
      if (result?.success) {
        ElMessage.success('添加成功')
      } else {
        ElMessage.error(result.message || '添加失败')
        return
      }
    }

    dialogVisible.value = false
    loadActivities()
  } catch (error) {
    if (error === false) {
      // 表单验证失败
      return
    }
    console.error('提交表单错误:', error)
    ElMessage.error(error.message || (activityForm.id ? '更新失败' : '添加失败'))
  }
}

// 图片上传前校验
const beforeUploadImage = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('上传头像图片只能是 JPG/PNG 格式!')
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB!')
  }
  return isJPG && isLt2M
}

// 图片上传成功
const handleImageUploadSuccess = (response) => {
  if (response?.success) {
    activityForm.image = response.data.url
  } else {
    ElMessage.error('图片上传失败')
  }
}

// 页面加载时获取数据
onMounted(() => {
  loadActivities()
})
</script>

<style scoped>
.admin-content-page {
  padding: 20px;
}

.page-header h1 {
  color: #2c3e50;
  margin-bottom: 20px;
  font-size: 24px;
}

.header-actions {
  margin-bottom: 20px;
}

.search-container {
  display: flex;
  gap: 10px;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.dialog-footer {
  text-align: right;
}
</style>
